<?php

class AjaxController extends Uuch_BaseController{ 
    
    public function init(){

    }
    
    public function  provinceAction()
    {
        $parentid=$this->getSafeParam("parentid");
        if(!$parentid)
            $parentid=0;
        if($parentid){
            $Countrys=  Application_Model_city::GetByParentId($parentid,"Array");
            echo json_encode($Countrys);
            exit;
        }
        else
        {
            exit;
        }
    }
    
    public function  addaddressAction()
    {
        $userid=$this->currentUser()->id;
        $newItem=new Application_Model_address();        
        $newItem->state=$this->getSafeParam("countryid");//所在国家
        $newItem->province=$this->getSafeParam("province");
        $newItem->city=$this->getSafeParam("City");
        $newItem->street=$this->getSafeParam("add");
        $newItem->comment="";
        $newItem->postcode=$this->getSafeParam("postcode");
        $newItem->linkMan=$this->getSafeParam("linkman");
        $newItem->mobile=$this->getSafeParam("tel");
        $newItem->phone=$this->getSafeParam("phone");
        $newItem->userId=$userid;
        $newItem->default=time();//默认值
        $newItem->save();
        $this->json($newItem->Id);
    }
    
    //编辑
    public function editstoreremarkAction()
    {
        $id=$this->getSafeParam("id");
        if($id){
            $editItem=new Application_Model_StoreItem($id);
            $editItem->remark=$this->getSafeParam("remark");

            $id=$editItem->save();        
            echo json_encode($editItem->id);            
        }
        exit;
    }
    
    public function uploadAction(){

        // Check the upload
        if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
                echo "ERROR:invalid upload";
                exit(0);
        }

        // Get the image and create a thumbnail
        $img = imagecreatefromjpeg($_FILES["Filedata"]["tmp_name"]);
        if (!$img) {
                echo "ERROR:could not create image handle ". $_FILES["Filedata"]["tmp_name"];
                exit(0);
        }

        $width = imageSX($img);
        $height = imageSY($img);

        if (!$width || !$height) {
                echo "ERROR:Invalid width or height";
                exit(0);
        }

        // Build the thumbnail
        $target_width = 100;
        $target_height = 100;
        $target_ratio = $target_width / $target_height;

        $img_ratio = $width / $height;

        if ($target_ratio > $img_ratio) {
                $new_height = $target_height;
                $new_width = $img_ratio * $target_height;
        } else {
                $new_height = $target_width / $img_ratio;
                $new_width = $target_width;
        }

        if ($new_height > $target_height) {
                $new_height = $target_height;
        }
        if ($new_width > $target_width) {
                $new_height = $target_width;
        }

        $new_img = ImageCreateTrueColor($target_width, $target_height);
        if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, 0)) {     // Fill the image black
                echo "ERROR:Could not fill new image";
                exit(0);
        }

        if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
                echo "ERROR:Could not resize image";
                exit(0);
        }

        if (!isset($_SESSION["file_info"])) {
                $_SESSION["file_info"] = array();
        }

        $path = 'data/'.date('Y-m').'/';
        Uuch_Util::create_folders($path);
        $file_id = $path.md5($_FILES["Filedata"]["tmp_name"] + rand()*100000).'.jpg';
        $tt = imagejpeg($new_img,$file_id);
        
        Uuch_Util::create_folders('big/'.$path);
        move_uploaded_file($_FILES["Filedata"]["tmp_name"], 'big/'.$file_id);
        
        if($tt){
            //echo $file_id;
            $this->json($file_id);
        }
        else
            $this->json(0);
    }
    
    public function getcouponAction(){
        if(!$this->isLogin()){
            printf('not login');
            $this->json('请重新登录后再添加领取');
            return;
        }
        $no = $this->getSafeParam('BatchNo');
        $batch = Application_Model_CouponBatch::getByNo($no);
        $message = NULL;
        if(!$batch->IsVaild($this->currentUser()->Id, $message)){
            $this->json($message);
            return;
        }
        $coupon = $batch->createCoupon();
        $coupon->UserId = $this->currentUser()->Id;
        $coupon->DateExpired =  date("Y-m-d",strtotime("+15day"));
        $coupon->save();
        $coupon->No = $batch->No.'00'.$coupon->Id;
        $coupon->save();
        $batch->GiveCount++;
        $batch->save();
        $this->json('恭喜您!优惠券领取成功.');
    }
    
    public function getawardAction(){
        if(!$this->isLogin()){
            $this->json(array('Value'=>-1,'message'=>'请登录后再领取优惠券'));
            return;
        }
        
        $userHistory = Application_Model_CampaignHistory::getByCampaignAndUserId(1,  $this->currentUser()->Id);
        $billHistory = Application_Model_RechargeBill::getByUserId($this->currentUser()->Id, Application_Model_PayBill::PAY_STATUS_SUCCESS ,'2013-06-01');
        
        if(count($userHistory) >= count($billHistory)){
            $this->json(array('Value'=>-1,'message'=>'您的抽奖次数已经用完了,请再次充值后再试'));
            return;
        }
        
        $result = NULL;
        $val = rand(1, 100);
        if($val<70){
            $result = 10;
        }else if($val <80){
            $result = 20;
        }else if($val <90){
            $result = 30;
        }else if($val < 95){
            $result = 50;
        }else{
            $result = 100;
        }
        
        $batch = Application_Model_CouponBatch::getByNo('DW');
        $coupon = $batch->createCoupon();
        $coupon->UserId = $this->currentUser()->Id;
        $coupon->Discount = $result;
        $coupon->Name .= ':'. $result .'元折扣';
        $coupon->save();
        
                
        $ah = new Application_Model_AwardHistory();
        $ah->UserName = $this->currentUser()->Nikename;
        $ah->AwardName = $result.'元折扣券';
        $ah->AddTime = date('Y-m-d H:i:s');
        $ah->save();
        
        $ch = new Application_Model_CampaignHistory();
        $ch->UserId = $this->currentUser()->Id;
        $ch->CampaignId = Application_Model_CampaignHistory::DWAWARD;
        $ch->DateCreated = date('Y-m-d H:i:s');
        $ch->Description = $coupon->Name;
        $ch->save();
                
        $this->json(array('Value'=>1,'coupon'=>$result));
    }
}

